import React, { useState } from 'react';
import { toast } from '@/lib/toast-with-audio';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell, Legend } from 'recharts';
import { motion } from 'framer-motion';
import { useTheme } from '@/hooks/useTheme';

// 图表数据（保留）
const projectProgressData = [
  { name: '权限系统', value: 75 },
  { name: '支付中心', value: 60 },
  { name: '用户中心', value: 45 },
  { name: '订单中心', value: 90 },
  { name: '消息平台', value: 80 },
  { name: '商品管理', value: 30 }
];

const bugDistributionData = [
  { name: '前端', value: 35, color: '#ff8c66' },
  { name: '后端', value: 27, color: '#22c55e' },
  { name: '数据库', value: 18, color: '#6366f1' },
  { name: 'UI/UX', value: 12, color: '#ec4899' },
  { name: '基础设施', value: 8, color: '#fbbf24' }
];

// 进度条组件
const ProgressBar: React.FC<{ progress: number }> = ({ progress }) => {
  return (
    <div className="w-full bg-gray-200 rounded-full h-1.5 mt-2">
      <div 
        className="h-full rounded-full" 
        style={{ width: `${progress}%`, backgroundColor: '#2563eb' }}
      ></div>
    </div>
  );
};

// 任务完成率圆环组件
const TaskCompletionCircle: React.FC = () => {
  // 计算圆环路径
  const radius = 40;
  const circumference = 2 * Math.PI * radius;
  const strokeDashoffset = circumference - (78 / 100) * circumference;
  
  return (
    <div className="h-52 flex flex-col justify-center items-center">
      <div className="relative w-40 h-40">
        <svg viewBox="0 0 36 36" className="absolute">
          <circle 
            cx="18" 
            cy="18" 
            r={radius / 2.5} 
            fill="none" 
            stroke="#e5e7eb" 
            strokeWidth="2"
          ></circle>
          <path 
            d={`M 18 2.0845 a ${radius / 2.5} ${radius / 2.5} 0 0 1 0 ${2 * radius / 2.5} a ${radius / 2.5} ${radius / 2.5} 0 0 1 0 ${-2 * radius / 2.5}`} 
            fill="none" 
            stroke="#2563eb" 
            strokeWidth="2" 
            strokeDasharray={circumference / 2.5}
            strokeDashoffset={strokeDashoffset / 2.5}
          ></path>
        </svg>
        <div className="absolute inset-0 flex items-center justify-center flex-col">
          <span className="text-2xl font-bold text-blue-600">78%</span>
          <span className="text-xs text-gray-500 mt-1">完成率</span>
        </div>
      </div>
    </div>
  );
};

// 活动项组件
const ActivityItem: React.FC<{ activity: { id: number; user: string; content: string; target: string; targetClass: string; icon: string; iconClass: string; time: string; targetText?: string } }> = ({ activity }) => {
  return (
    <motion.div 
      key={activity.id}
      className="flex items-start p-3 bg-gray-50 dark:bg-gray-700 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-600 transition-colors"
      whileHover={{ x: 5 }}
    >
      <div className="flex-shrink-0 mr-3">
        <div className={`w-10 h-10 rounded-full ${activity.iconClass} flex items-center justify-center`}>
          <i className={`fa-solid ${activity.icon}`}></i>
        </div>
      </div>
      <div className="flex-1 min-w-0">
        <div className="text-gray-800 dark:text-gray-200 flex justify-between">
          <span className="font-medium">{activity.user}</span>
          <span className="text-xs text-gray-500 dark:text-gray-400 whitespace-nowrap">{activity.time}</span>
        </div>
        <p className="text-sm text-gray-600 dark:text-gray-300 mt-1">
          {activity.content}
          <span className={`${activity.targetClass}`}>{activity.target}</span>
          {activity.targetText}
        </p>
      </div>
    </motion.div>
  );
};

// 待办事项组件
const TodoItem: React.FC<{ todo: { id: number; title: string; project: string; projectClass: string; description: string; progress?: number; completed?: boolean } }> = ({ todo }) => {
  return (
    <div className="flex items-center py-2">
      <label className="flex items-center cursor-pointer">
        <div className="relative">
          <input 
            type="checkbox" 
            className={`w-5 h-5 border-2 rounded-md ${todo.completed ? 'border-green-500 bg-green-500' : 'border-gray-300'}`}
            checked={todo.completed}
            readOnly
          />
          {todo.completed && (
            <i className="fa-solid fa-check text-white text-xs absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2"></i>
          )}
        </div>
      </label>
      <div className="ml-3 flex-1">
        <div className="flex justify-between items-center">
          <span className={`font-medium ${todo.completed ? 'text-gray-600 line-through' : 'text-gray-800'}`}>
            {todo.title}
          </span>
          <span className={`text-xs ${todo.projectClass}`}>项目: {todo.project}</span>
        </div>
        <div className="text-sm text-gray-600 mt-1">{todo.description}</div>
        {!todo.completed && <ProgressBar progress={todo.progress || 0} />}
      </div>
    </div>
  );
};

// 快速创建按钮组件
const QuickCreateButton: React.FC<{ icon: string; text: string; bgClass: string; textClass: string }> = ({ icon, text, bgClass, textClass }) => {
  return (
    <button 
      className={`w-full ${bgClass} dark:${bgClass.replace('50', '900/20')} hover:${bgClass.replace('50', '100')} dark:hover:${bgClass.replace('50', '900/30')} ${textClass} dark:${textClass.replace('700', '300')} py-3 rounded-lg mb-3 flex items-center justify-center transition-colors`}
      onClick={() => toast(`创建${text}`)}
    >
      <i className={`fa-solid ${icon} text-xl mr-2`}></i>
      {text}
    </button>
  );
};

// 知识库项组件
const KnowledgeItem: React.FC<{ item: { id: number; title: string; description: string } }> = ({ item }) => {
  return (
    <a href="#" className="block p-3 bg-gray-50 dark:bg-gray-700 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded-lg transition-colors">
      <div className="text-sm font-medium text-blue-700 dark:text-blue-300 mb-1">{item.title}</div>
      <p className="text-xs text-gray-600 dark:text-gray-300">{item.description}</p>
    </a>
  );
};

// 团队动态项组件
const TeamUpdateItem: React.FC<{ update: { id: number; content: string; avatar?: string; avatarClass?: string; icon?: string; iconClass?: string; time: string } }> = ({ update }) => {
  return (
    <div className="flex items-center">
      <div className={`w-8 h-8 rounded-full ${update.avatarClass || update.iconClass} flex items-center justify-center mr-3`}>
        {update.avatar ? (
          update.avatar
        ) : (
          <i className={`fa-solid ${update.icon}`}></i>
        )}
      </div>
      <div>
        <div className="text-sm text-gray-800 dark:text-gray-200">{update.content}</div>
        <div className="text-xs text-gray-500 dark:text-gray-400 mt-1">{update.time}</div>
      </div>
    </div>
  );
};

export default function Home() {
  const { isDark } = useTheme();
  const [searchTerm, setSearchTerm] = useState('');
  
  // 模拟数据（应该从store获取）
  const recentActivities = [
    { 
      id: 1, 
      user: '李工程师', 
      content: '更新了需求 RBAC-128 的状态为: ', 
      target: '开发中',
      targetClass: 'text-blue-600',
      icon: 'fa-file-lines',
      iconClass: 'bg-blue-100 text-blue-600',
      time: '10分钟前'
    },
    { 
      id: 2, 
      user: '张开发', 
      content: '合并了分支 ', 
      target: 'feature/payment',
      targetClass: 'font-mono',
      icon: 'fa-code-branch',
      iconClass: 'bg-green-100 text-green-600',
      time: '45分钟前'
    },
    { 
      id: 3, 
      user: '王测试', 
      content: '提交了Bug报告 ', 
      target: '#BUG-2047',
      targetClass: 'text-red-500',
      icon: 'fa-bug',
      iconClass: 'bg-orange-100 text-orange-600',
      time: '2小时前'
    },
    { 
      id: 4, 
      user: '周产品经理', 
      content: '评论了任务 ', 
      target: '#TASK-0451',
      targetClass: 'text-green-600',
      targetText: ': 需要调整UI交互细节',
      icon: 'fa-comment',
      iconClass: 'bg-purple-100 text-purple-600',
      time: '3小时前'
    },
    { 
      id: 5, 
      user: '钱架构师', 
      content: '部署了预发布环境 ', 
      target: 'version 1.8.5-rc1',
      targetClass: 'font-mono',
      icon: 'fa-git-branch',
      iconClass: 'bg-blue-100 text-blue-600',
      time: '5小时前'
    }
  ];

  const todos = [
    { 
      id: 1, 
      title: '评审RBAC权限设计方案', 
      project: '权限系统', 
      projectClass: 'status-badge info',
      description: '需求提交人: 周产品经理',
      progress: 33
    },
    { 
      id: 2, 
      title: '解决BUG-2050支付超时问题', 
      project: '紧急', 
      projectClass: 'status-badge danger',
      description: '预计2小时完成',
      progress: 25
    },
    { 
      id: 3, 
      title: '编写API接口文档', 
      project: '用户中心', 
      projectClass: 'status-badge info',
      description: '截止: 今天 18:00',
      progress: 75
    },
    { 
      id: 4, 
      title: '参与敏捷迭代会议', 
      project: '已完成', 
      projectClass: 'status-badge success',
      description: '已完成，结果在知识库查看',
      completed: true
    },
    { 
      id: 5, 
      title: '更新依赖库版本', 
      project: '技术改进', 
      projectClass: 'status-badge warning',
      description: '升级至Spring Boot 3.1.0',
      progress: 50
    }
  ];

  const knowledgeBaseItems = [
    { id: 1, title: 'CI/CD 最佳实践', description: '最新部署流程规范与优化建议' },
    { id: 2, title: '微服务架构设计指南', description: '分布式系统设计原则和常见方案' },
    { id: 3, title: '性能优化手册', description: '高并发系统调优策略和工具使用' },
    { id: 4, title: 'Git规范V2.0', description: '分支管理、提交信息与工作流优化' }
  ];

  const teamUpdates = [
    { 
      id: 1, 
      content: '陈前端工程师完成了用户中心改版', 
      avatar: '陈',
      avatarClass: 'bg-blue-100 text-blue-600',
      time: '42分钟前'
    },
    { 
      id: 2, 
      content: '敏捷迭代Sprint 15结束，达成率92%', 
      icon: 'fa-check',
      iconClass: 'bg-green-100 text-green-600',
      time: '1小时前'
    },
    { 
      id: 3, 
      content: '生产环境v1.8.4成功发布', 
      icon: 'fa-server',
      iconClass: 'bg-purple-100 text-purple-600',
      time: '2小时前'
    },
    { 
      id: 4, 
      content: '周四 15:00 技术分享会 - Kubernetes实践', 
      icon: 'fa-calendar',
      iconClass: 'bg-blue-100 text-blue-600',
      time: '4小时前'
    }
  ];

  const handleSearch = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      toast.info(`搜索: ${searchTerm}`);
    }
  };

  const handleCreateTask = () => {
    toast.success('创建新任务');
  };

  const handleMarkAllComplete = () => {
    toast.success('所有任务已标记为完成');
  };

  return (
    <div>
      <div className="mb-6">
        <motion.div 
          className="mb-8"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5 }}
        >
          <h1 className="text-2xl font-bold text-gray-800 dark:text-gray-100">Dashboard</h1>
          <p className="text-gray-600 dark:text-gray-400 mt-1">产品、项目与任务的实时数据概览</p>
        </motion.div>
        
      </div>
      
      {/* 图表区域 */}
      <div className="grid grid-cols-3 gap-6 mb-6">
        {/* 项目进度图表 */}
        <motion.div 
          initial={{ opacity: 0, scale: 0.95 }}
          animate={{ opacity: 1, scale: 1 }}
          transition={{ duration: 0.3 }}
          className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-5"
        >
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-lg font-semibold text-gray-700 dark:text-gray-200">项目进度</h2>
            <span className="text-blue-600 dark:text-blue-400">
              <i className="fa-solid fa-arrow-trend-up"></i>
            </span>
          </div>
          <div className="h-64">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart
                data={projectProgressData}
                margin={{ top: 20, right: 15, bottom: 30, left: 45 }}
              >
                <CartesianGrid strokeDasharray="3 3" vertical={false} />
                <XAxis 
                  dataKey="name" 
                  stroke={"#888"}
                  tick={{ fontSize: 12 }}
                />
                <YAxis 
                  stroke={"#888"}
                  tickFormatter={(value: number) => `${value}%`} 
                  splitLine={{ lineStyle: { strokeDasharray: '3 3' } }}
                />
                <Tooltip formatter={(value: number) => [`${value}%`, '进度']} />
                <Bar 
                  dataKey="value" 
                  barWidth={16}
                  radius={[8, 8, 0, 0]}
                  label={{
                    position: 'top' as const,
                    formatter: (value: number) => `${value}%`
                  }}
                >
                  {projectProgressData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={['#3B82F6', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6', '#06B6D4'][index % 6]} />
                  ))}
                </Bar>
              </BarChart>
            </ResponsiveContainer>
          </div>
        </motion.div>
        
        {/* 缺陷分布图表 */}
        <motion.div 
          initial={{ opacity: 0, scale: 0.95 }}
          animate={{ opacity: 1, scale: 1 }}
          transition={{ duration: 0.3, delay: 0.1 }}
          className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-5"
        >
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-lg font-semibold text-gray-700 dark:text-gray-200">缺陷分布</h2>
            <span className="text-orange-500 dark:text-orange-400">
              <i className="fa-solid fa-circle-exclamation"></i>
            </span>
          </div>
          <div className="h-64">
            <ResponsiveContainer width="100%" height="100%">
              <PieChart>
                <Pie
                  data={bugDistributionData}
                  cx="50%"
                  cy="50%"
                  innerRadius={60}
                  outerRadius={80}
                  fill="#8884d8"
                  paddingAngle={2}
                  dataKey="value"
                  label={({ name, value }) => `${name} ${value}`}
                  labelLine={false}
                >
                  {bugDistributionData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={entry.color} />
                  ))}
                </Pie>
                <Tooltip formatter={(value, name) => [`${value}个缺陷`, name]} />
                <Legend verticalAlign="bottom" height={36} />
              </PieChart>
            </ResponsiveContainer>
          </div>
        </motion.div>
        
        {/* 任务完成率 */}
        <motion.div 
          initial={{ opacity: 0, scale: 0.95 }}
          animate={{ opacity: 1, scale: 1 }}
          transition={{ duration: 0.3, delay: 0.2 }}
          className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-5 col-span-1 w-full"
        >
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-lg font-semibold text-gray-700 dark:text-gray-200">任务完成率</h2>
            <span className="text-green-500 dark:text-green-400">
              <i className="fa-solid fa-circle-check"></i>
            </span>
          </div>
          <TaskCompletionCircle />
        </motion.div>
      </div>
      
      {/* 主内容区域 */}
      <div className="grid grid-cols-3 gap-6">
        {/* 左侧两列 */}
        <div className="col-span-2">
          {/* 最近活动记录 */}
          <motion.div 
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.3, delay: 0.3 }}
            className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-5 mb-6"
          >
            <div className="flex justify-between items-center mb-4">
              <h2 className="text-lg font-semibold text-gray-700 dark:text-gray-200">最近活动记录</h2>
              <button className="text-sm text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300 flex items-center">
                查看全部
                <i className="fa-solid fa-chevron-right ml-1"></i>
              </button>
            </div>
            
            <div className="space-y-4">
              {recentActivities.map(activity => (
                <ActivityItem key={activity.id} activity={activity} />
              ))}
            </div>
          </motion.div>
          
          {/* 产品进度 */}
          <motion.div 
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.3, delay: 0.4 }}
            className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-5"
          >
            <div className="flex justify-between items-center mb-5">
              <h2 className="text-lg font-semibold text-gray-700 dark:text-gray-200">产品进度</h2>
              <div className="flex space-x-2">
                <button 
                  className="text-xs text-gray-500 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-400"
                  onClick={() => toast.info('查看产品详情')}
                >
                  查看详情
                </button>
                <button 
                  className="text-sm text-blue-600 dark:text-blue-400 hover:text-blue-800 dark:hover:text-blue-300"
                  onClick={() => toast.info('刷新产品进度')}
                >
                  <i className="fa-solid fa-refresh"></i>
                </button>
              </div>
            </div>
            
            <div className="space-y-4">
              {/* 产品进度卡片 */}
              <div className="grid grid-cols-2 gap-4">
                {/* 权限系统 */}
                <div className="bg-blue-50 dark:bg-blue-900/20 rounded-lg p-4">
                  <div className="flex justify-between items-center mb-2">
                    <span className="text-sm font-medium text-blue-700 dark:text-blue-300">权限系统</span>
                    <i className="fa-solid fa-shield text-blue-500"></i>
                  </div>
                  <div className="text-lg font-bold text-blue-800 dark:text-blue-200">75%</div>
                  <div className="w-full bg-blue-200 dark:bg-blue-700 rounded-full h-2 mt-2">
                    <div className="h-full bg-blue-500 rounded-full" style={{ width: '75%' }}></div>
                  </div>
                </div>
                
                {/* 支付中心 */}
                <div className="bg-green-50 dark:bg-green-900/20 rounded-lg p-4">
                  <div className="flex justify-between items-center mb-2">
                    <span className="text-sm font-medium text-green-700 dark:text-green-300">支付中心</span>
                    <i className="fa-solid fa-credit-card text-green-500"></i>
                  </div>
                  <div className="text-lg font-bold text-green-800 dark:text-green-200">60%</div>
                  <div className="w-full bg-green-200 dark:bg-green-700 rounded-full h-2 mt-2">
                    <div className="h-full bg-green-500 rounded-full" style={{ width: '60%' }}></div>
                  </div>
                </div>
                
                {/* 用户中心 */}
                <div className="bg-purple-50 dark:bg-purple-900/20 rounded-lg p-4">
                  <div className="flex justify-between items-center mb-2">
                    <span className="text-sm font-medium text-purple-700 dark:text-purple-300">用户中心</span>
                    <i className="fa-solid fa-users text-purple-500"></i>
                  </div>
                  <div className="text-lg font-bold text-purple-800 dark:text-purple-200">45%</div>
                  <div className="w-full bg-purple-200 dark:bg-purple-700 rounded-full h-2 mt-2">
                    <div className="h-full bg-purple-500 rounded-full" style={{ width: '45%' }}></div>
                  </div>
                </div>
                
                {/* 订单中心 */}
                <div className="bg-orange-50 dark:bg-orange-900/20 rounded-lg p-4">
                  <div className="flex justify-between items-center mb-2">
                    <span className="text-sm font-medium text-orange-700 dark:text-orange-300">订单中心</span>
                    <i className="fa-solid fa-shopping-cart text-orange-500"></i>
                  </div>
                  <div className="text-lg font-bold text-orange-800 dark:text-orange-200">90%</div>
                  <div className="w-full bg-orange-200 dark:bg-orange-700 rounded-full h-2 mt-2">
                    <div className="h-full bg-orange-500 rounded-full" style={{ width: '90%' }}></div>
                  </div>
                </div>
              </div>
              
              {/* 进度统计 */}
              <div className="flex justify-between items-center text-sm text-gray-600 dark:text-gray-400 mt-4">
                <span>平均进度: 67.5%</span>
                <span>4个产品</span>
              </div>
            </div>
          </motion.div>
        </div>
        
        {/* 右侧列 */}
        <div className="space-y-6">
          {/* 快速创建 */}
          <motion.div 
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.3, delay: 0.5 }}
            className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-5"
          >
            <h2 className="text-lg font-semibold text-gray-700 dark:text-gray-200 mb-5">快速创建</h2>
            <QuickCreateButton 
              icon="fa-clipboard-list" 
              text="新建需求" 
              bgClass="bg-blue-50" 
              textClass="text-blue-700"
            />
            <QuickCreateButton 
              icon="fa-check-square" 
              text="创建任务" 
              bgClass="bg-indigo-50" 
              textClass="text-indigo-700"
            />
            <QuickCreateButton 
              icon="fa-bug" 
              text="报告缺陷" 
              bgClass="bg-red-50" 
              textClass="text-red-700"
            />
          </motion.div>
          
          {/* 知识库推荐 */}
          <motion.div 
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.3, delay: 0.6 }}
            className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-5"
          >
            <h2 className="text-lg font-semibold text-gray-700 dark:text-gray-200 mb-5">知识库推荐</h2>
            <div className="space-y-4">
              {knowledgeBaseItems.map(item => (
                <KnowledgeItem key={item.id} item={item} />
              ))}
            </div>
          </motion.div>
          
          {/* 团队动态 */}
          <motion.div 
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.3, delay: 0.7 }}
            className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-5"
          >
            <h2 className="text-lg font-semibold text-gray-700 dark:text-gray-200 mb-5">团队动态</h2>
            <div className="space-y-4">
              {teamUpdates.map(update => (
                <TeamUpdateItem key={update.id} update={update} />
              ))}
            </div>
          </motion.div>
        </div>
      </div>
    </div>
  );
}